package com.kkkkkba.search.controller;

import com.google.code.kaptcha.Producer;
import com.kkkkkba.search.common.BaseResponse;
import com.kkkkkba.search.common.ResultUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@Slf4j
@Api(tags = "验证码接口")
public class ValidateController {

    @Autowired
    private Producer captchaProducer;

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ServletOutputStream out = response.getOutputStream();
        String verifyCode = captchaProducer.createText();   // 生成验证码
        System.out.println(verifyCode);   // 控制台打印验证码
        BufferedImage verifyCodeImage = captchaProducer.createImage(verifyCode);   // 生成验证码图片
        ImageIO.write(verifyCodeImage, "jpg", out);   // 输出验证码图片流
        request.getSession().setAttribute("verifyCode", verifyCode);   // 将验证码存入Session
    }

    @PostMapping("/validate")
    public BaseResponse<Boolean> validate(@RequestParam String code, HttpServletRequest request) {
        String verifyCode = (String) request.getSession().getAttribute("verifyCode");
        request.getSession().removeAttribute("verifyCode");   // 验证后清除Session中的验证码
        System.out.println(verifyCode+" "+code.toLowerCase());
        Boolean ans = verifyCode != null && verifyCode.equals(code.toLowerCase());
        return ResultUtils.success(ans);   // 区分验证码输入大小写
    }


}
